package com.flying.set;

import javax.swing.*;
import java.util.*;

/**
 * @author 刘鹏飞
 * @ClassName TreeSetTest1
 * @Date 2025/1/11 19:44
 * @Created by 刘鹏飞
 * @Description  测试TreeSet存储自定义对象
 */
public class TreeSetTest1 {

    public static void main(String[] args) {

        // TreeSet存储自定义类对象
        // 1. 自定义类实现自然排序接口  Comparator<>


        Set<Person> set=new TreeSet<>();


        Person person = new Person("百里守约",24);
        Person person1 = new Person("百里玄策",20);
        Person person2 = new Person("镜",26);
        Person person3 = new Person("伽罗",32);
        Person person4 = new Person("苏烈",26);

        set.add(person);
        set.add(person);
        set.add(person1);
        set.add(person2);
        set.add(person3);
        set.add(person4);


        for (Person person5 : set) {
            System.out.println(person5);
        }


        System.out.println("====================================================");

        // 初始化 TreeSet容器时 传入一个另一个Set型容器


        Set<Student> suHashSet=new HashSet<>();


        Student student = new Student("百里守约",24);
        Student student1 = new Student("百里玄策",20);
        Student student2 = new Student("镜",26);
        Student student3 = new Student("伽罗",32);
        Student student4 = new Student("苏烈",26);

        suHashSet.add(student);
        suHashSet.add(student1);
        suHashSet.add(student2);
        suHashSet.add(student3);
        suHashSet.add(student4);



//        Set<Student> suSet=new TreeSet<>(suHashSet);  //  传入容器的元素对象也需要实现 自然排序


        // 在 TreeSet容器初始化时,传入一个定制比较器


        Set<Student> students = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1==null || o2==null){
                    throw new RuntimeException("对象为空!");
                }

                int age = o1.getAge();
                int age1 = o2.getAge();

                return age==age1 ? -o1.getName().compareTo(o2.getName()) : -Integer.compare(age,age1);

            }
        });


        students.add(student);
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);


        for (Student student5 : students) {
            System.out.println("student5 = " + student5);
        }



        // 操作






    }







}
